package com.whut.monitor.netty.handler;


import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;


/**
 * @author 徐雅
 * 模型文件发送处理-暂时不用这种机制
 */
@Service("FileServerHandler")
@Sharable
public class FileServerHandler extends ChannelInboundHandlerAdapter {
    private static final Logger logger = Logger.getLogger(FileServerHandler.class); //取得logger

    //收到客户端消息时
    @Override
    public void channelRead(ChannelHandlerContext ctx,Object msg) throws Exception {
        logger.info("收到客户端发来的消息：" + msg.toString());
        String flag1="SConnected";
        String flag2="SLoadFailed";
        String flag3="SLoadSuccess";
        if(msg.toString().equals(flag1)||msg.toString().equals(flag2))
        {
            // 发送文件所在路径
            String url="C:/Users/Administrator/Desktop/math.docx";
            // 为ByteBuf分配字节
            ByteBuf encodedres = ctx.alloc().buffer(4 *url.length());
            encodedres.writeBytes(url.getBytes());
            ctx.writeAndFlush(encodedres);
            /*//文件开始传输前发送文件信息
            FileEntity fileEntity= FileUtil.getFileProperty();
            ByteBuf encoded = ctx.alloc().buffer(4 * (int) FileUtil.filesize); //为ByteBuf分配字节
            encoded.writeBytes(fileEntity.toString().getBytes());
            ctx.writeAndFlush(encoded);
            //开始传输文件
            File file=new File("C:/Users/Administrator/Desktop/math.docx");
            byte[] buffer=new byte[(int)file.length()];
            FileInputStream in=null;
            try {
                  in=new FileInputStream(file);
                  ByteArrayOutputStream byteout = new ByteArrayOutputStream();
                  ByteBuf encodedFile = ctx.alloc().buffer(4 * (int) FileUtil.filesize);
                  while(in.read(buffer)!=-1){    //read()--int，-1表示读取完毕
                       byteout.write(buffer);
                       encodedFile.writeBytes(buffer);
                       ctx.writeAndFlush(encodedFile);
                  }
                  in.close();
                 } catch (FileNotFoundException e) {
                          e.printStackTrace();
            }*/
        }
        else if(msg.toString().equals(flag3))
        {
            String response="update success";
            // 为ByteBuf分配字节
            ByteBuf encodedres = ctx.alloc().buffer(4 *response.length());
            encodedres.writeBytes(response.getBytes());
            ctx.writeAndFlush(encodedres);
        }
        else
        {
            String response="server have received the wrong message from client："+msg.toString();
            // 为ByteBuf分配字节
            ByteBuf encodedres = ctx.alloc().buffer(4 *response.length());
            encodedres.writeBytes(response.getBytes());
            ctx.writeAndFlush(encodedres);
        }
    }

    // 通道打开时
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        logger.info("文件传输：来自" + ctx.channel().remoteAddress() + "的连接已打开");
    }

    // 通道关闭时
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        logger.info("文件传输：来自" + ctx.channel().remoteAddress() + "的连接已关闭");
    }

    // 异常
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        logger.info("文件传输：来自" + ctx.channel().remoteAddress() + "的连接出现异常,cause=" + cause.getMessage());
        ctx.close();
    }
}